import { useMemo, useState } from 'react'
import { Button, Upload, Result } from 'antd'
import { CloudUploadOutlined, SelectOutlined, LoadingOutlined } from '@ant-design/icons'
import { useParams, useNavigate } from 'react-router-dom'
import { useMessage } from '@/hooks/useMessage'
import { uploadFile, saveDocMessage } from '@/apis/file'
import { convertDocToTiptap } from '@/utils/docToTiptapConverter'
import { getUserId } from '@/utils/token'
import style from './index.module.less'

export const UploadFile = ({ value, onChange, maxCount = 1 }) => {
    const { success, error, contextHolder } = useMessage()
    const param = useParams()
    const navigate = useNavigate()
    const [loading, setLoading] = useState(false)
    
    const beforeUpload = async (file) => {
        let id = ''
        if (param.id !== undefined) id = param.id
        setLoading(true)
        
        try {
            // 检查文件类型
            const isDocFile = file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx')
            
            if (isDocFile) {
                // 处理DOC文件
                await handleDocFile(file)
            } else {
                // 处理其他文件类型
                await uploadFile({ id, file });
                onChange?.(file);
            }
            
            success({
                content: isDocFile ? '文档导入成功' : '上传文件成功',
                callBack: () => {
                    setLoading(false)
                    if (param.id === undefined) navigate(`/home`, { state: { refresh: Date.now() } })
                    else navigate(`/home/list/${param.id}`, { state: { refresh: Date.now() } })
                }
            })
        } catch (e) {
            if (e.response?.data?.message === '文件已存在，请重新命名或选择其他文件夹上传') {
                error({
                    content: '文件已存在，请重新命名或选择其他文件夹上传',
                    callBack: () => setLoading(false)
                })
            } else {
                error({
                    content: isDocFile ? '文档导入失败' : '上传文件失败',
                    callBack: () => setLoading(false)
                })
            }
        }
        return false; // 阻止默认上传行为
    };

    // 处理DOC文件的函数
    const handleDocFile = async (file) => {
        try {
            // 转换DOC文件为Tiptap JSON格式
            const tiptapJson = await convertDocToTiptap(file)
            
            // 确保内容格式正确
            if (!tiptapJson || !tiptapJson.content || !Array.isArray(tiptapJson.content)) {
                throw new Error('文档转换失败：内容格式不正确')
            }
            
            // 如果内容为空，添加一个默认段落
            if (tiptapJson.content.length === 0) {
                tiptapJson.content = [
                    {
                        type: "paragraph",
                        attrs: { textAlign: null },
                        content: [{ type: "text", text: "文档内容" }]
                    }
                ]
            }
            
            // 获取用户ID
            const userId = getUserId()
            if (!userId) {
                throw new Error('用户未登录')
            }
            
            // 从文件名中提取文档名称（去掉扩展名）
            const docName = file.name.replace(/\.(doc|docx)$/i, '')
            
            // 准备保存文档的数据
            const docData = {
                docName: docName,
                userId: userId,
                docContent: JSON.stringify(tiptapJson), // 将对象转换为JSON字符串
                isBelongToKnowledgeBase: param.id ? "1" : "0", // 如果有知识库ID，则归属于知识库
                knowledgeBaseId: param.id || null
            }
            
            // 调用保存文档接口
            const response = await saveDocMessage(docData)
            
            if (response.code !== 200) {
                throw new Error(response.msg || '保存文档失败')
            }
        
            // 触发父组件的回调
            onChange?.(file)
            
        } catch (error) {
            console.error('处理DOC文件失败:', error)
            throw error
        }
    }

    const handleChange = ({ file }) => {
        if (file && file.status !== 'removed') {
            onChange?.(file)
        } else {
            onChange?.(undefined)
        }
    }

    const fileList = useMemo(() => {
        if (value && value.status !== 'removed') {
            return [value]
        }
        return undefined
    }, [])

    return (
        <>
            {contextHolder}
            <Upload
                fileList={fileList}
                beforeUpload={beforeUpload}
                onChange={handleChange}
                maxCount={maxCount}
                showUploadList={false}
                className={style.box}
                accept=".doc,.docx,.pdf,.txt,.xlsx,.xls,.ppt,.pptx"
            >
                <Button type='default'>
                    <CloudUploadOutlined className={style.firIcon} />
                    上传文件
                    <SelectOutlined className={style.secIcon} />
                </Button>
            </Upload>
            {
                loading ?
                    <div className={style.fullScreen}>
                        <Result
                            icon={<LoadingOutlined />}
                            title='系统正在处理文件，请稍等'
                            status='info'
                        />
                    </div>
                    : <></>
            }
        </>
    )
}